﻿//-----------------------------------------------------------------------
// <copyright>
// This file is subject to the terms and conditions of the Microsoft Public License (MS-PL).
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL for more details.
// </copyright>
//----------------------------------------------------------------------- 
namespace Fulcrum.ViewModelGenerator
{
    #region Usings

    using System;
    using System.Xml.Linq;

    #endregion Usings

    public static class XElementExtensions
    {
        #region RequiredAttribute

        public static XAttribute RequiredAttribute(this XElement element, XName name)
        {
            if (null == element)
            {
                throw new ArgumentNullException("element");
            }

            if (null == name)
            {
                throw new ArgumentNullException("name");
            }

            var attribute = element.Attribute(name);

            string attributeValue = (string)attribute;
            if (String.IsNullOrWhiteSpace(attributeValue))
            {
                throw new ArgumentNullException(name.ToString());
            }

            return attribute;
        }

        #endregion RequiredAttribute

        #region OptionalAttribute

        public static XAttribute OptionalAttribute(this XElement element, XName name, object defaultValue)
        {
            if (null == element)
            {
                throw new ArgumentNullException("element");
            }

            if (null == name)
            {
                throw new ArgumentNullException("name");
            }

            var attribute = element.Attribute(name);
            if (null == attribute)
            {
                attribute = new XAttribute(name, defaultValue);
            }

            return attribute;
        }

        #endregion OptionalAttribute

        public static T OptionalEnumAttribute<T>(this XElement element, XName name, T defaultValue)
        {
            if (null == element)
            {
                throw new ArgumentNullException("element");
            }

            if (null == name)
            {
                throw new ArgumentNullException("name");
            }

            var attribute = element.Attribute(name);
            if (null == attribute)
            {
                return defaultValue;
            }

            var value = (T) Enum.Parse(typeof(T), (string) attribute, true);
            return value;
        }


    }
}
